import Taro, { Component } from '@tarojs/taro'
import { View, Input, Image, Button } from '@tarojs/components'
import { connect } from '@tarojs/redux'

import { sign, signed } from './../../actions/counter'
import allExtrance from './../../config/allExtrance'
import phoneLogin from './../../api/phoneLogin'
import './signIn.less'
import allRequest from '../../api/allRequest';
import config from './../../config/domian'

let _this

@connect(({ counter }) => ({
    counter
}), (dispatch) => ({
    sign() {
        dispatch(sign())
    },
    signed() {
        dispatch(signed())
    },
}))
class SignIn extends Component {
    constructor(props) {
        super(props)
        this.state = {
            agreeXie: true,   //是否同意协议
            phoneSign: false,   // 是否输入手机号登陆
            errorPhone: false,   //手机号码格式是否错误
            phone: '',    //手机号码
            coding: false,
            countNumber: 60, //倒计时初始
            code: ''
        }
    }


    componentWillReceiveProps(nextProps) {
        console.log(nextProps.counter, "nextprops")
    }

    componentDidMount() {
        _this = this
        //检测开发环境，开发环境使用万能code
        if (process.env.NODE_ENV === 'development') {
            let code = config[process.env.NODE_ENV].code
            this.setState({ code })
        }
        // this.props.sign()
    }

    componentWillUnmount() { }

    componentDidShow() { }

    componentDidHide() { }

    chooseXie(e) {
        let { agreeXie } = this.state;
        this.setState({ agreeXie: !agreeXie })
    }

    tapPhoneSign(e) {
        e.stopPropagation();
        _this.setState({ phoneSign: true })
    }

    getPhoneNumber(e) {
        e.stopPropagation();
        let detail = e.detail
        Taro.login().then(res => {
            if (res.code) {
                //发起网络请求
                allExtrance.util.Taro.showLoading('登录中')
                phoneLogin.phoneLogin({ code: res.code, ...detail }).then(data => {
                    if (data) {
                        if (this.props.isConsumer) {
                            Taro.redirectTo({
                                url: '/pages/consumer/index/index'
                            })
                        } else {
                            this.props.onRefresh()
                        }
                        this.props.signed()
                    }
                })
                    .catch(err => { allExtrance.util.Taro.showToast('拒绝授权无法使用小程序，请重新登录') })
            } else {
                console.log('登录失败！' + res.errMsg)
            }
        }).catch(err =>{
            allExtrance.util.Taro.showToast('登录取消')
        })
    }

    messageVerify(value) {
        let showToast = allExtrance.util.Taro.showToast
        return new Promise((resolve, reject) => {
            if (value.phone == '') {
                showToast('请填写手机号码')
                reject(false)
            }
            if (value.code == '') {
                showToast('请输入验证码')
                reject(false)
            }
            if (!value.agreeXie) {
                showToast('未同意协议，无法登录')
                reject(false)
            }
            resolve(true)
        })

    }

    signIn(e) {
        let { phone, agreeXie, code } = _this.state
        let value = {
            phone,
            agreeXie,
            code
        }
        _this.messageVerify(value)
            .then(res => {
                if (res) {
                    allExtrance.util.Taro.setStorageSync('phone', phone)
                    phoneLogin.phoneLogin({ phone, code })
                        .then(data => {
                            if (data) {
                                _this.props.onRefresh()
                                _this.props.signed()
                            }
                        })
                        .catch(err => { allExtrance.util.Taro.showToast(err) })
                }
            })
            .catch(err => { console.log(err) })
    }


    // 手机号码验证正则
    checkPhone(e) {
        if (Taro.getEnv() === Taro.ENV_TYPE.WEB) {
            this.forceScroll()
        }
        let phone = e.detail.value;
        if (phone != '') {
            let valid_rule = /^(13[0-9]|14[5-9]|15[012356789]|166|17[0-8]|18[0-9]|19[8-9])[0-9]{8}$/;// 手机号码校验规则
            if (!valid_rule.test(phone)) {
                this.setState({ errorPhone: true }, () => {
                    allExtrance.util.Taro.showToast('手机号码格式有误')
                })
            } else {
                this.setState({ errorPhone: false, phone })
            }
        }
    }
    //验证码
    listenCode(e) {
        if (process.env.NODE_ENV === 'production') {
            let code = e.detail.value;
            if (code == '000000') {
                code = config[process.env.NODE_ENV].code
            }
            this.setState({ code })
        }
    }
    //获取验证码
    getCode(e) {
        let { errorPhone, phone } = this.state
        if (!errorPhone && phone != "") {
            allRequest.verifyPhone({ phone }).then((result) => {
                allExtrance.util.Taro.showToast(result.__info)
                this.setState({
                    countNumber: 60
                }, () => {
                    let { countNumber } = this.state
                    this.setState({
                        coding: true
                    })
                    let interval = setInterval(() => {
                        if (countNumber > 0) {
                            this.setState({
                                countNumber: --countNumber
                            })
                        } else {
                            this.setState({
                                coding: false
                            })
                            clearInterval(interval)
                            return
                        }
                    }, 1000)
                })
            }).catch((err) => {
                allExtrance.util.Taro.showToast(err)
            });
        } else if (!errorPhone && phone == "") {
            allExtrance.util.Taro.showToast('手机号码不得为空')
        } else {
            allExtrance.util.Taro.showToast('手机号码格式有误')
        }
    }
    //前往服务协议
    toXieyi(e) {
        Taro.navigateTo({
            url: '/subPackages/subPackageS/protocol/protocol?type=worker'
        })
    }

    hideSign(e) {
        // if (this.props.cannotHide) {
        //     return
        // }
        this.props.signed()
        if (this.props.back) {
            Taro.redirectTo({
                url: '/pages/loading/loading'
            })
        }
    }

    stopPropagation(e) {
        e.stopPropagation()
    }

    //强制页面归位
    forceScroll(e) {
        window.scroll(0, 0);
    }

    render() {
        let { agreeXie, phoneSign, errorPhone, coding, countNumber } = this.state
        return (
            <View className='index'>
                {this.props.counter.signStatus && <View className='signIn'>
                    <View className='zhezhao' onClick={this.hideSign.bind(this)}>
                        <View className='signBlock' onClick={this.stopPropagation.bind(this)}>
                            {
                                !phoneSign && <View className='signInter'>
                                    <View className='signRow row'>登录或注册{Taro.getStorageSync('name')}</View>
                                    {
                                        Taro.getEnv() === Taro.ENV_TYPE.WEAPP ?
                                            <View className='signRow row'>
                                                <Button className='btn' open-type='getPhoneNumber' onGetPhoneNumber={this.getPhoneNumber.bind(this)}>
                                                    <View className='signBtn wechat row'>
                                                        <Image className='icon' src='https://file.open.banchengyun.com/2019/04/19/155563739417354.png' />
                                                        <View className='btnCon'>微信账号快速注册</View>
                                                    </View>
                                                </Button>
                                            </View> :
                                            <View className='signBtn phone row' onClick={this.tapPhoneSign.bind(this)}>
                                                <Image className='icon' src='https://file.open.banchengyun.com/2019/04/19/155563739486735.png' />
                                                <View className='btnCon'>手机号注册/登录</View>
                                            </View>
                                    }
                                    {
                                        process.env.NODE_ENV === 'development' && Taro.getEnv() === Taro.ENV_TYPE.WEAPP
                                        && <View className='signBtn phone row' onClick={this.tapPhoneSign.bind(this)} style='margin:0'>
                                            <Image className='icon' src='https://file.open.banchengyun.com/2019/04/19/155563739486735.png' />
                                            <View className='btnCon'>手机号注册/登录</View>
                                        </View>
                                    }
                                </View>
                            }
                            {
                                phoneSign && <View className='signInter'>
                                    <View className='signRow row'>欢迎登录{Taro.getStorageSync('name')}</View>
                                    <Input className={`signInput allInput ${errorPhone ? 'errorPhone' : ''}`} placeholder='请输入手机号码' placeholderClass='inputHolder' cursorSpacing='100' type='number' name='phone' onBlur={this.checkPhone.bind(this)} style={`border:1px solid ${Taro.getStorageSync('baseColor')}`} />
                                    {
                                        Taro.getEnv() === Taro.ENV_TYPE.WEB && <View className='yanzheng'>
                                            <Input className='yanInput allInput' placeholder='请输入验证码' placeholderClass='inputHolder' type='number' onInput={this.listenCode.bind(this)} onBlur={this.forceScroll.bind(this)} style={`background-color:${Taro.getStorageSync('baseColor')}`} />
                                            {
                                                coding
                                                    ? <View className='signYan gray' style={`background-color:${Taro.getStorageSync('baseColor')}`}>重新发送({countNumber}s)</View>
                                                    : <View className='signYan' onClick={this.getCode.bind(this)} style={`background-color:${Taro.getStorageSync('baseColor')}`}>{countNumber == 0 ? '重新获取' : '获取验证码'}</View>
                                            }
                                        </View>
                                    }
                                    <View className='xieyi'>
                                        {agreeXie ? <Image className='icon' onClick={this.chooseXie.bind(this)} src='https://file.open.banchengyun.com/2019/04/19/155564090138218.png' /> :
                                            <Image className='icon' onClick={this.chooseXie.bind(this)} src='https://file.open.banchengyun.com/2019/04/19/155563907894334.png' />}
                                        <View className='xieCon'>登录即表示同意<View className='xieStrong' onClick={this.toXieyi.bind(this)}>《{JSON.parse(Taro.getStorageSync("saasConfig")).company_protocol_title}》</View></View>
                                    </View>
                                    {(!errorPhone && agreeXie) ? <View className='loginInAg' onClick={this.signIn.bind()} style={`background-color:${Taro.getStorageSync('baseColor')}`}>登录</View> : <View className='loginIn' onClick={this.signIn.bind()} style={`background-color:${Taro.getStorageSync('baseColor')}`}>登录</View>}
                                </View>
                            }

                        </View>
                    </View>
                </View>}
            </View>
        )
    }
}

export default SignIn
